<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { createComboDataApi, updateComboDataApi, getComboDataApi, deleteComboDataApi } from "@/api/combo-jd"
import { type IGetComboData } from "@/api/combo/types/combo"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { CirclePlus, Search, Refresh } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { useUserStore } from "@/store/modules/user"
defineOptions({
  name: "ComboSelectDy"
})
const userStore = useUserStore()
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive<any>({ data: { type: "dy", packageType: "号卡" } })
const formRules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入套餐名称" }],
  package_super: [{ required: true, trigger: "blur", message: "请选择套餐" }],
  operator: [{ required: true, trigger: "blur", message: "请选择运营商" }],
  type: [{ required: true, trigger: "blur", message: "请选择平台类型" }],
  packageType: [{ required: true, trigger: "blur", message: "请选择套餐类型" }],
  code: [{ required: true, trigger: "blur", message: "请输入商品Skuid" }]
  // systemId: [{ required: true, trigger: "change", message: "请输入系统对应套餐" }]
})
//合集套餐
import { getCompailationDataApi } from "@/api/combo"
const switchValue = ref<any>(false)
const comboHJList = ref<any>([])
const getComboHjList = () => {
  getCompailationDataApi({
    page: 1,
    size: 1000,
    team: userStore.teamName
  })
    .then((res: any) => {
      comboHJList.value = res.data.list
    })
    .catch(() => {
      comboHJList.value = []
    })
}
getComboHjList()
const changeComboType = () => {
  formData.data.systemId = ""
  formData.data.heId = ""
}

const handleAdd = () => {
  dialogVisible.value = true
}
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      uploadFuc()
    } else {
      return false
    }
  })
}
const uploadFuc = async () => {
  if (!formData.data.systemId && !formData.data.heId) {
    ElMessage.warning("请选择套餐或者合集套餐！")
    return
  }
  if (currentUpdateId.value === undefined) {
    await createComboDataApi(formData.data).then(() => {
      ElMessage.success("新增成功")
      dialogVisible.value = false
      getTableData()
    })
  } else {
    await updateComboDataApi(formData.data).then(() => {
      ElMessage.success("修改成功")
      dialogVisible.value = false
      getTableData()
    })
  }
}
//#endregion

//#region 删
const handleDelete = (row: IGetComboData) => {
  ElMessageBox.confirm(`正在删除套餐：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteComboDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: any) => {
  console.log(row)
  currentUpdateId.value = row.id
  formData.data = row
  formData.data.id = currentUpdateId.value
  formData.data.userId = row.userId
  switchValue.value = !!row.heId
  dialogVisible.value = true
}
//#endregion

//#region 查
// 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  name: "",
  code: ""
})

const tableData = ref<IGetComboData[]>([])
const getTableData = () => {
  loading.value = true
  getComboDataApi({
    name: searchData.name || "",
    code: searchData.code || "",
    type: "dy",
    userId: userStore.usernameID,
    page: paginationData.currentPage,
    size: paginationData.pageSize
  })
    .then((res: any) => {
      paginationData.total = res.data.total
      tableData.value = res.data.list
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
    console.log("重置")
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
    console.log("查询")
  }
  paginationData.currentPage = 1
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
/**监听套餐缓存(pinia) */
import { useComboStore } from "@/store/modules/combo"
const comboStore = useComboStore()
comboStore.getComoboFn()
const comboList = ref<any>([])
watch(
  [() => formData.data.packageType],
  (newValue) => {
    console.log(newValue.flat())
    if (newValue.flat()[0] === "宽带") {
      getList()
    } else {
      comboStore.getComoboFn()
    }
  },
  {
    immediate: true
  }
)
watch(
  [() => comboStore.comboListStore],
  (newValue) => {
    comboList.value = newValue.flat()
  },
  {
    immediate: true
  }
)
/**department END */
/**宽带套餐获取 */
// 接口
import { getWebSteDataApi } from "@/api/webSet"
const getList = () => {
  loading.value = true
  getWebSteDataApi({
    page: 1,
    size: 1000,
    state: "上架"
  })
    .then((res: any) => {
      comboList.value = res.data.list
    })
    .catch(() => {
      comboList.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

// ** 清除规则报错信息
const clearValidate = () => {
  formRef.value?.clearValidate()
}
const resetForm = () => {
  formData.data = { type: "dy", packageType: "号卡" }
  switchValue.value = false
  currentUpdateId.value = undefined

  clearValidate()
}
// const formatterCombo = (row: any, column: any, celValue: any) => {
//   comboList.value.filter((item: any) => {
//     if (item.id == row.systemId) {
//       celValue = item.name
//     }
//   })
//   return celValue
// }

// #region 团队名展示
import { useTeamStore } from "@/store/modules/team"
const teamStore = useTeamStore()
const tableDataB = ref<any[]>([])
teamStore.getTeamFn()
watch(
  [() => teamStore.teamListStore],
  (newValue) => {
    tableDataB.value = newValue.flat()
  },
  { immediate: true }
)
const formatterTeam = (row: any, column: any, celValue: any) => {
  tableDataB.value.filter((item: any) => {
    if (item.id == row.userId) {
      celValue = item.name
    }
    // console.log(item, 8888888)
  })
  return celValue
}
// #endregion
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="抖音套餐名">
          <el-input v-model.trim="searchData.name" placeholder="请输入抖音套餐名" />
        </el-form-item>
        <el-form-item prop="code" label="商品Skuid">
          <el-input v-model.trim="searchData.code" placeholder="请输入抖音商品Skuid" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="handleAdd">添加套餐</el-button>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="teamName" label="团队名" :formatter="formatterTeam" align="center" />
          <el-table-column prop="name" label="抖音套餐名" align="center" />
          <el-table-column prop="code" label="商品Skuid" align="center" />
          <el-table-column prop="packageType" label="套餐类型" align="center" />
          <el-table-column prop="systemName" label="系统对应套餐" align="center" width="220" />
          <el-table-column prop="operator" label="运营商" align="center">
            <template #default="scope">
              <span v-if="scope.row.operator == 1">移动</span>
              <span v-else-if="scope.row.operator == 2">联通</span>
              <span v-else-if="scope.row.operator == 3">电信</span>
              <span v-else-if="scope.row.operator == 4">广电</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="280" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增套餐' : '修改套餐'"
      @close="resetForm"
      width="40%"
    >
      <el-form ref="formRef" :model="formData.data" :rules="formRules" label-width="110px" label-position="left">
        <el-form-item prop="name" label="套餐名">
          <el-input v-model="formData.data.name" placeholder="请输入" style="width: 240px" />
        </el-form-item>
        <el-form-item prop="code" label="商品Skuid">
          <el-input v-model="formData.data.code" placeholder="请输入抖音商品Skuid" style="width: 240px" />
        </el-form-item>
        <el-form-item prop="packageType" label="套餐类型">
          <el-select v-model="formData.data.packageType" clearable filterable placeholder="请选择" style="width: 240px">
            <el-option :key="1" label="号卡" value="号卡" />
            <el-option :key="2" label="宽带" value="宽带" />
          </el-select>
        </el-form-item>
        <el-form-item prop="systemId" label="系统对应套餐">
          <el-select
            v-if="!switchValue && formData.data.packageType === '号卡'"
            v-model="formData.data.systemId"
            clearable
            filterable
            placeholder="请选套餐"
            style="width: 240px"
          >
            <el-option
              v-for="item in comboList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.state === 'false'"
            />
          </el-select>
          <el-select
            v-else-if="switchValue && formData.data.packageType === '号卡'"
            v-model="formData.data.heId"
            clearable
            filterable
            placeholder="请选合集套餐,可输入快速查询"
            style="width: 240px"
          >
            <!-- :value="item.id + ''" -->
            <el-option v-for="item in comboHJList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-select
            v-else
            v-model="formData.data.systemId"
            clearable
            filterable
            placeholder="请选套餐"
            style="width: 240px"
          >
            <el-option v-for="item in comboList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <span style="margin-left: 10px" v-if="formData.data.packageType === '号卡'"
            >切换为合集套餐 <el-switch v-model="switchValue" @change="changeComboType"
          /></span>
        </el-form-item>
        <el-form-item prop="operator" label="运营商">
          <el-select v-model="formData.data.operator" clearable placeholder="请选择" style="width: 240px">
            <el-option :key="1" label="移动" :value="1" />
            <el-option :key="2" label="联通" :value="2" />
            <el-option :key="3" label="电信" :value="3" />
            <el-option :key="4" label="广电" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item prop="type" label="平台类型">
          <el-select v-model="formData.data.type" clearable placeholder="请选择" style="width: 240px" disabled>
            <el-option :key="1" label="京东" value="jd" />
            <el-option :key="2" label="抖音" value="dy" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.ageInput :deep(.el-input) {
  width: 20% !important;
}
:deep(.el-popper) {
  max-width: 50% !important;
}
:deep(.el-cascader) {
  width: 567px !important;
}
.text-ellipsis {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
</style>
